<template>
  <div class="page-account">
    <div :class="[ fullWidth > 768 ? 'containerSamll':'containerBig']" class="container">
      <swiper v-if="fullWidth>768" :options="swiperOption" class="swiperPross">
        <swiper-slide class="swiperPic">
          <img src="https://img.alicdn.com/imgextra/i3/289589474/O1CN01G8R4KF2Jr8whuGoPP_!!289589474.jpg">
        </swiper-slide>
      </swiper>
      <div class="index_from page-account-container" style="position:relative;">
        <div class="page-account-top"></div>

        <Tabs v-if="loginType==='account'" value="name1" class="mt10">
          <TabPane label="密码登录" name="name1">
            <Form ref="formInline" :model="formInline" :rules="ruleInline" @keyup.enter="handleSubmit('formInline')">
              <FormItem prop="username">
                <Input v-model="formInline.username" type="text" prefix="ios-contact-outline" placeholder="请输入用户名" size="large"></Input>
              </FormItem>
              <FormItem prop="password">
                <Input v-model="formInline.password" type="password" prefix="ios-lock-outline" placeholder="请输入密码" size="large"></Input>
              </FormItem>
              <FormItem prop="code">
                <div class="code">
                  <Input v-model="formInline.code" type="text" prefix="ios-keypad-outline" placeholder="请输入验证码" size="large"></Input>
                  <img :src="imgcode" class="pictrue" @click="captchas">
                </div>
              </FormItem>
              <FormItem>
                <Button style="border-radius: 40px;" type="primary" long size="large" class="btn" @click="handleSubmit('formInline')">{{
              $t('page.login.submit') }}
                </Button>
              </FormItem>
              <FormItem>没有账户?
                <a style="margin-left:0px;" @click="toRegister">
                  立即注册
                </a>
              </FormItem>
            </Form>
          </TabPane>
          <TabPane label="邮箱登录" name="name2">
            <Form ref="formMsg" :model="formMsg" :rules="ruleMsg" @keyup.enter="handleSubmit('formMsg')">
              <FormItem prop="phone">
                <Input v-model.trim="formMsg.phone" type="text" maxlength="50" prefix="ios-contact-outline" placeholder="邮箱" size="large"></Input>
              </FormItem>
              <FormItem prop="code">
                <div class="code">
                  <Input v-model.trim="formMsg.code" type="text" prefix="ios-keypad-outline" placeholder="验证码" size="large"></Input>
                  <Button style="border-radius: 40px;margin-left:20px;" type="primary" long :disabled="disabled" :class="disabled === true ? 'on' : ''" size="large" class="btn code" @click="handleSendCode('formMsg')">{{ text }}
                  </Button>
                </div>
              </FormItem>
              <FormItem>
                <Button style="border-radius: 40px;" type="primary" long size="large" class="btn" @click="handleSubmitMsg('formMsg')">{{
              $t('page.login.submit') }}
                </Button>
              </FormItem>
              <FormItem>没有账户?
                <a style="margin-left:0px;" @click="toRegister">
                  立即注册
                </a>
              </FormItem>
            </Form>
          </TabPane>
        </Tabs>
      </div>
    </div>
    <Modal v-model="modalsBind" :mask-closable="false" :z-index="2" scrollable footer-hide closable title="绑定手机号" width="342" @on-cancel="cancel">
      <Form ref="formBind" :model="formBind" :rules="ruleBind" @keyup.enter="handleSubmitBind('formBind')">
        <FormItem>
        </FormItem>
        <FormItem prop="phone">
          <Input v-model="formBind.phone" type="text" maxlength="11" prefix="ios-contact-outline" placeholder="请输入手机号" size="large"></Input>
        </FormItem>
        <FormItem prop="smscode">
          <div class="code">
            <Input v-model="formBind.smscode" type="text" style="width:180px;" prefix="ios-keypad-outline" placeholder="请输入验证码" size="large"></Input>
            <Button style="border-radius: 40px;margin-left:20px;" type="primary" :disabled="disabled" :class="disabled === true ? 'on' : ''" size="large" class="btn code" @click="handleSendCodeBind()">{{ text }}
            </Button>
          </div>
        </FormItem>
        <FormItem>
          <Button type="primary" style="border-radius: 40px;" long size="large" class="btn" @click="handleSubmitBind('formBind')">绑定
          </Button>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="modals" :mask-closable="false" :z-index="2" scrollable footer-hide closable title="请完成安全校验" width="342">
      <div class="captchaBox">
        <div id="captcha" ref="captcha" style="position: relative" />
        <div id="msg" />
      </div>
    </Modal>

    <Modal v-model="modals_code" :mask-closable="false" :z-index="2" scrollable footer-hide closable title="请完成安全校验" width="342">
      <div class="captchaBox">
        <div id="captcha_code" ref="captcha_code" style="position: relative" />
        <div id="msg_code" />
      </div>
    </Modal>
  </div>
</template>
<script>
import { AccountLogin, loginInfoApi, SendLoginCodeApi, WxLoginBindPhone } from '@/api/account'
import mixins from '../mixins'
import sendVerifyCode from "@/mixins/SendVerifyCode";
import Setting from '@/setting'
import util from '@/libs/util'
import '@/assets/js/canvas-nest.min'
import '@/assets/js/jigsaw.js'
import { validateTell } from '@/utils/validate'

export default {
  mixins: [mixins, sendVerifyCode],
  name: 'index',
  data () {
    return {
      fullWidth: document.documentElement.clientWidth,
      swiperOption: {
        pagination: '.swiper-pagination',
        autoplay: true
      },
      loginType: 'account',
      loginPwdSms: 'pwd',
      modals: false,
      modals_code: false,
      modalsBind: false,
      qrcodeShow: true,
      autoLogin: true,
      imgcode: '',
      //   formInline: {
      //     username: 'choasmida',
      //     password: '123456',
      //     code: 'so',
      //     type: 'password'
      //   },
      formInline: {
        username: 'admin',
        password: 'xfeater123',
        code: 'so',
        type: 'password'
      },
      formMsg: {
        phone: '',
        code: ''
      },
      formBind: {
        phone: '',
        smscode: ''
      },
      ruleInline: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      ruleMsg: {
        phone: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: this.handleEmail }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      ruleBind: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: this.handleTell }
        ],
        smscode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      errorNum: 0,
      jigsaw: null,
      jigsaw_code: null,
      login_logo: '',
      defaultSwiperList: require('@/assets/images/sw.jpg'),
      wx_data: {}, // 微信二维码对象信息
      qrcode_url: '', // 微信二维码对象信息
      interval: null,
      qrCode_interval: null,
      mSgType: '',
    }
  },
  watch: {
    fullWidth (val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function () {
          // 打印screenWidth变化的值
          that.timer = false
        }, 400)
      }
    },
    $route (n) {
      console.log(n)
      this.captchas()
    }
  },
  created () {
    var _this = this
    top !== window && (top.location.href = location.href)
    document.onkeydown = function (e) {
      if (_this.$route.name === 'login') {
        const key = window.event.keyCode
        if (key === 13) {
          _this.handleSubmit('formInline')
        }
      }
    }
    window.addEventListener('resize', this.handleResize)
  },
  mounted: function () {
    this.$nextTick(() => {
      /* eslint-disable */
      const that = this
      this.jigsaw = Jigsaw.init({
        el: this.$refs.captcha,
        onSuccess () {
          console.log('我试试执行了')
          that.modals = false
          that.closeModel()
        },
        onFail: this.closefail,
        onRefresh () {
        }
      })
      if (this.screenWidth < 768) {
        document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg')
      } else {
        document.getElementsByTagName('canvas')[0].className = 'index_bg'
      }
      this.swiperData()
    })
    this.captchas()

    // 发送验证码
    this.$nextTick(() => {
      /* eslint-disable */
      const that = this;
      var p = '';
      var type = 'login';
      this.jigsaw_code = Jigsaw.init({
        el: this.$refs.captcha_code,
        onSuccess () {
          that.modals_code = false;
          if (that.loginType == 'wx') { // 微信绑定手机号
            p = that.formBind.phone;
            type = 'login_bind';
          } else {// 手机号登陆
            p = that.formMsg.phone;
          }
          SendCodeApi({ phone: p, type: type }).then(async res => {
            if (res.status === 200) {
              that.$Notice.success({ title: '发送成功' })
              that.sendCode()
            } else {
              that.$Message.error(res.msg)
            }
          }).catch(res => {
            that.$Message.error(res.msg);
          })
        },
        onFail: that.closefail_code,
        onRefresh () {
        }
      })
      if (this.screenWidth < 768) {
        document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg')
      } else {
        document.getElementsByTagName('canvas')[0].className = 'index_bg'
      }
    })
  },
  beforeCreate () {
    if (this.fullWidth < 768) {
      document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg')
    } else {
      document.getElementsByTagName('canvas')[0].className = 'index_bg'
    }
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize)
    document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg')
  },
  methods: {
    // 正则 核验电话
    handleTell (rule, value, callback) {
      if (validateTell(value) === false) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    },
    // 正则 核验邮箱
    handleEmail (rule, value, callback) {
      var myreg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
      if (!myreg.test(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    },
    cancel () {
      this.qrCode()
      this.qrCode_interval = setInterval(this.qrCode, 10000)
    },
    swiperData () {
      loginInfoApi().then(res => {
        const data = res.data || {}
        this.login_logo = data.login_logo ? data.login_logo : require('@/assets/images/logo.png')
      }).catch(res => {
        this.$Message.error(res.msg)
      })
    },
    // 登录成功后的逻辑
    async accountSuccess (res) {
      const msg = this.$Message.loading({
        content: '登录中...',
        duration: 0
      })
      msg()
      const expires = this.getExpiresTime(res.data.expires_time)
      // 记录用户登陆信息
      util.cookies.set('uuid', res.data.user_info.id, {
        expires: expires
      })
      util.cookies.set('token', res.data.token, {
        expires: expires
      })
      util.cookies.set('expires_time', res.data.expires_time, {
        expires: expires
      })
      util.cookies.setDomain('userInfo', '11111222222333333333', {
        expires: expires
      })

      const db = await this.$store.dispatch('admin/db/database', {
        user: true
      })
      // 保存菜单信息
      db.set('menus', res.data.menus).set('unique_auth', res.data.unique_auth).set('user_info', res.data.user_info).write()
      // 记录用户信息
      this.$store.dispatch('admin/user/set', {
        name: res.data.user_info.account,
        avatar: res.data.user_info.head_pic,
        access: res.data.unique_auth,
        logo: res.data.logo,
        logoSmall: res.data.logo_square,
        version: res.data.version,
        newOrderAudioLink: res.data.newOrderAudioLink
      })
      if (this.jigsaw) this.jigsaw.reset()
      return this.$router.replace({ path: this.$route.query.redirect || '/admin/' })
    },
    // 关闭模态框
    closeModel () {
      const msg = this.$Message.loading({
        content: '登录中...',
        duration: 0
      })
      let loginObj = {}
      if (this.loginPwdSms == 'pwd') {
        loginObj = {
          account: this.formInline.username,
          pwd: this.formInline.password,
          imgcode: this.formInline.code,
          type: 'account_login'
        }
      }
      if (this.loginPwdSms === 'sms') {
        loginObj = {
          account: this.formMsg.phone,
          smscode: this.formMsg.code,
          type: 'email_login'
        }
      }
      AccountLogin(loginObj).then(async res => {
        msg()
        const expires = this.getExpiresTime(res.data.expires_time)
        // 记录用户登陆信息
        util.cookies.set('uuid', res.data.user_info.id, {
          expires: expires
        })
        util.cookies.set('token', res.data.token, {
          expires: expires
        })
        util.cookies.set('expires_time', res.data.expires_time, {
          expires: expires
        })
        util.cookies.setDomain(res.data.domain_user_info)
        const db = await this.$store.dispatch('admin/db/database', {
          user: true
        })
        // 保存菜单信息
        db.set('menus', res.data.menus).set('unique_auth', res.data.unique_auth).set('user_info', res.data.user_info).write()
        // 记录用户信息
        this.$store.dispatch('admin/user/set', {
          name: res.data.user_info.account,
          avatar: res.data.user_info.head_pic,
          access: res.data.unique_auth,
          logo: res.data.logo,
          logoSmall: res.data.logo_square,
          version: res.data.version,
          newOrderAudioLink: res.data.newOrderAudioLink
        })
        if (this.jigsaw) this.jigsaw.reset()

        if (this.$route.query.return_url) {
          return window.location.href = this.$route.query.return_url
          // return window.open(this.$route.query.return_url)
        } else {
          return this.$router.replace({ path: this.$route.query.redirect || '/admin/' })
        }
      }).catch(res => {
        msg()
        const data = res === undefined ? {} : res
        this.errorNum++
        if (this.loginPwdSms === 'pwd') {
          this.captchas()
        }

        this.$Message.error(data.msg || '登录失败')
        if (this.jigsaw) this.jigsaw.reset()
      })
    },
    getExpiresTime (expiresTime) {
      const nowTimeNum = Math.round(new Date() / 1000)
      const expiresTimeNum = expiresTime - nowTimeNum
      return parseFloat(parseFloat(parseFloat(expiresTimeNum / 60) / 60) / 24)
    },
    closefail () {
      if (this.jigsaw) this.jigsaw.reset()
      this.$Message.error('校验错误')
    },
    handleResize (event) {
      this.fullWidth = document.documentElement.clientWidth
      if (this.fullWidth < 768) {
        document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg')
      } else {
        document.getElementsByTagName('canvas')[0].className = 'index_bg'
      }
    },
    captchas: function () {
      this.imgcode = Setting.apiBaseURL + '/captcha_pro?' + Date.parse(new Date())
    },
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.errorNum >= 2) {
            this.modals = true
          } else {
            this.loginPwdSms = 'pwd'
            this.closeModel()
          }
        }
      })
    },
    handleSubmitMsg (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.errorNum >= 2) {
            this.modals = true
          } else {
            this.loginPwdSms = 'sms'
            this.closeModel()
          }
        }
      })
    },
    // 绑定
    handleSubmitBind (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          WxLoginBindPhone(this.formBind).then(async res => {
            if (res.status === 200) {
              this.accountSuccess(res)
            } else {
              this.$Notice.warning({ title: res.msg })
            }
          }).catch(res => {
            this.$Notice.warning({ title: res.msg })
          })
        }
      })
    },
    closefail_code () {
      //   if (this.jigsaw_code) this.jigsaw_code.reset();
      this.$Message.error('校验错误')
    },
    // 发送验证码
    handleSendCode (name) {
      let phone = this.formMsg.phone
      // if (phone === '') {
      //   this.$Notice.warning({ title: '手机号不能为空' })
      //   return false
      // }
      // if (validateTell(phone) === false) {
      //   this.$Notice.warning({ title: '手机号格式错误' })
      //   return false
      // }
      // this.modals_code = true;
      if (this.jigsaw_code) this.jigsaw_code.reset();
      SendLoginCodeApi({ email: phone }).then(async res => {
        if (res.status === 200) {
          this.$Notice.success({ title: res.msg })
          // that.sendCode()
        } else {
          this.$Message.error(res.msg)
        }
      }).catch(res => {
        that.$Message.error(res.msg);
      })
    },

    // 去注册
    toRegister () {
      this.$router.push({ name: 'register' })
    },

  }
}
</script>
<style scoped>
.ivu-tabs-nav {
  width: 100%;
}
.ivu-tabs-tab {
  width: 50% !important;
}
</style>
<style scoped lang="stylus">
.page-account {
  display: flex;
}

.page-account .code {
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-account .code .pictrue {
  height: 40px;
}

.swiperPross {
  border-radius: 6px 0px 0px 6px;
}

.swiperPross, .swiperPic, .swiperPic img {
  width: 510px;
  height: 100%;
}

.swiperPic img {
  width: 100%;
  height: 100%;
}

.wx img {
  width: 300px;
}

.container {
  height: 400px !important;
  padding: 0 !important;
  /* overflow: hidden; */
  border-radius: 6px;
  z-index: 1;
  display: flex;
}

.containerSamll {
  /* width: 56% !important; */
  background: #fff !important;
  border: 1px solid #d9dde2;
  box-shadow: 2px 2px 5px #d9dde2;
}

.containerBig {
  width: auto !important;
  background: #f7f7f7 !important;
}

.index_from {
  padding: 0 40px 32px 40px;
  height: 400px;
  box-sizing: border-box;
}

.index_from .weChat {
  position: absolute;
  right: 12px;
  top: 14px;
  width: 195px;
  height: 52px;
  cursor: pointer;
}

.index_from .weChat .weChatIcon1 {
  width: 52px;
  height: 52px;
  float: right;
  background: url('https://img.alicdn.com/imgextra/i4/352758917/O1CN01jXxJvv2Fk2KmnvCOD_!!352758917.png') -79px 0 no-repeat;
  display: inline-block;
}

.index_from .changeWxLogin .weChatIcon1 {
  background: url('https://img.alicdn.com/imgextra/i4/352758917/O1CN01jXxJvv2Fk2KmnvCOD_!!352758917.png') -173px 0 no-repeat;
}

.index_from .weChat .weChatIcon2 {
  width: 132px;
  height: 25px;
  float: right;
  background: url('https://img.alicdn.com/imgextra/i4/352758917/O1CN01jXxJvv2Fk2KmnvCOD_!!352758917.png') -160px -390px no-repeat;
  display: inline-block;
}

.index_from .changeWxLogin .weChatIcon2 {
  background: url('https://img.alicdn.com/imgextra/i4/352758917/O1CN01jXxJvv2Fk2KmnvCOD_!!352758917.png') 25px -390px no-repeat;
}

.weChat .weChatDiv {
  position: absolute;
  width: 126px;
  height: 23px;
  left: 10px;
  top: 1px;
}

.weChat .weChatDiv .weChatIcon3 {
  width: 17px;
  height: 17px;
  float: left;
  margin-left: 10px;
  background: url('https://img.alicdn.com/imgextra/i4/352758917/O1CN01jXxJvv2Fk2KmnvCOD_!!352758917.png') 0 -110px no-repeat;
  display: inline-block;
  margin-top: 3px;
}

.changeWxLogin .weChatDiv .weChatIcon3 {
  width: 0;
}

.weChat .weChatDiv .weChatTit {
  width: 86px;
  height: 12px;
  text-align: left;
  font-size: 12px;
  line-height: 12px;
  color: #738299;
  float: right;
  margin-top: 5px;
  margin-right: 3px;
}

.page-account-top {
  padding: 20px 0 !important;
  box-sizing: border-box !important;
  display: flex;
  justify-content: center;
}

.page-account-container {
  border-radius: 0px 6px 6px 0px;
}

.btn {
  background: linear-gradient(90deg, rgba(25, 180, 241, 1) 0%, rgba(14, 115, 232, 1) 100%) !important;
}

.captchaBox {
  width: 310px;
}

input {
  display: block;
  width: 290px;
  line-height: 40px;
  margin: 10px 0;
  padding: 0 10px;
  outline: none;
  border: 1px solid #c8cccf;
  border-radius: 4px;
  color: #6a6f77;
}

#msg {
  width: 100%;
  line-height: 40px;
  font-size: 14px;
  text-align: center;
}

a:link, a:visited, a:hover, a:active {
  margin-left: 100px;
  color: #0366D6;
}

.index_from >>> .ivu-input-large {
  font-size: 14px !important;
}
</style>
